<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级" prop="classCode">
        <el-select
          v-model="queryParams.classCode"
          placeholder="请选择班级"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in classList"
            :key="item.classCode"
            :label="`${item.classCode} - ${item.className}`"
            :value="item.classCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="等级" prop="grade">
        <el-select
          v-model="queryParams.grade"
          placeholder="请选择等级"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="dict in gradeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="磨耳朵时长" prop="listenDuration">
        <el-input
          v-model="queryParams.listenDuration"
          placeholder="请输入磨耳朵时长"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="积分数" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入积分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="提交日期" prop="submitDate">
        <el-date-picker clearable
          v-model="queryParams.submitDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择提交日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="应交日期" prop="dueDate">
        <el-date-picker clearable
          v-model="queryParams.dueDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择应交日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['eduManage:submit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['eduManage:submit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['eduManage:submit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['eduManage:submit:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['eduManage:submit:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="submitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="提交ID" align="center" prop="submitId" /> -->
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="班级编码" align="center" prop="classCode" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="提交状态" align="center" prop="submitStatus">
        <template slot-scope="scope">
          <el-tag
            :type="getSubmitStatusTagType(scope.row.submitStatus)"
            size="small"
          >
            {{ getSubmitStatusText(scope.row.submitStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="作业内容" align="center" prop="submitContent" />
      <el-table-column label="作业评语" align="center" prop="submitComment" />
      <el-table-column label="等级" align="center" prop="submitGradeName" />
      <el-table-column label="积分数" align="center" prop="score" />
      <el-table-column label="磨耳朵时长" align="center" prop="listenDuration" />
      <el-table-column label="提交日期" align="center" prop="submitDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.submitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应交日期" align="center" prop="dueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="submitDatetime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['eduManage:submit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['eduManage:submit:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改作业提交记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级编码" prop="classCode">
          <el-select v-model="form.classCode" placeholder="请选择班级编码" @change="handleClassChange" clearable>
            <el-option
              v-for="classItem in classList"
              :key="classItem.classCode"
              :label="classItem.classCode + ' - ' + classItem.className"
              :value="classItem.classCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="班级名称" readonly />
        </el-form-item>
        <el-form-item label="学生信息" prop="studentNo">
          <el-select v-model="form.studentNo" placeholder="请选择学生" @change="handleStudentChange" clearable :disabled="!form.classCode">
            <el-option
              v-for="student in studentList"
              :key="student.studentNo"
              :label="student.studentName"
              :value="student.studentNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="学生姓名" readonly />
        </el-form-item>
        <el-form-item label="作业内容">
          <editor v-model="form.submitContent" :min-height="192"/>
        </el-form-item>
<el-form-item label="作业评语" prop="submitComment">
  <el-select
    v-model="form.submitComment"
    filterable
    allow-create
    default-first-option
    placeholder="请选择或输入评语"
    style="width: 100%"
  >
    <el-option
      v-for="item in commentOptions"
      :key="item.commentId"
      :label="item.content"
      :value="item.content"
    />
  </el-select>
</el-form-item>
        <el-form-item label="等级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择等级" clearable>
            <el-option
              v-for="dict in gradeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="积分数" prop="score">
          <el-input v-model="form.score" placeholder="请输入积分数" />
        </el-form-item>
        <el-form-item label="提交状态" prop="submitStatus">
          <el-select v-model="form.submitStatus" placeholder="请选择提交状态" clearable>
            <el-option
              v-for="status in submitStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            >
              <el-tag :type="getSubmitStatusTagType(status.value)" size="mini">
                {{ status.label }}
              </el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提交日期" prop="submitDate" style="display: none;">
          <el-date-picker clearable
            v-model="form.submitDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择提交日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="提交时间" prop="submitDatetime">
          <el-date-picker clearable
            v-model="form.submitDatetime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择提交时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="应交日期" prop="dueDate">
          <el-date-picker clearable
            v-model="form.dueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择应交日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="importVisible" width="400px" append-to-body>
      <el-form ref="uploadForm" :model="upload" label-width="80px">
        <el-form-item label="选择班级" prop="classCode">
          <el-select v-model="upload.classCode" placeholder="请选择班级" style="width: 100%" @change="handleClassCodeChange">
            <el-option
              v-for="dict in classList"
              :key="dict.classCode"
              :label="dict.className"
              :value="dict.classCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应交日期" prop="dueDate">
          <el-date-picker clearable
            v-model="upload.dueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择应交日期"
            @change="handleDueDateChange">
          </el-date-picker>
        </el-form-item>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :data="upload.data" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleFileError" :before-upload="beforeUpload" :auto-upload="true" :name="'file'" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <span>导入文件命名格式为【班级编码_作业提交记录】。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubmit, getSubmit, delSubmit, addSubmit, updateSubmit } from "@/api/manage/submit"
import { listComment } from "@/api/manage/comment"
import { listClass } from "@/api/manage/class"
import { listStudent } from "@/api/manage/student"
import { getDicts } from "@/api/system/dict/data";


export default {
  name: "Submit",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作业提交记录表格数据
      submitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示导入对话框
      importVisible: false,
      // 班级列表
      classList: [],
      // 学生列表
      studentList: [],
      // 等级选项
      gradeOptions: [],
      // 提交状态选项
      submitStatusOptions: [
        { value: '0', label: '未交' },
        { value: '1', label: '已提交' },
        { value: '2', label: '迟交' },
        { value: '3', label: '补觉' }
      ],
      // 评语选项
      commentOptions: [],
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/eduManage/submit/importData",
        // 上传的数据
        data: { classCode: '', dueDate: '' },
        // 弹出层标题
        title: "",
        // 选择的班级编码
        classCode: undefined,
        // 选择的应交日期
        dueDate: undefined
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        classCode: null,
        submitStatus: null,
        submitContent: null,
        submitComment: null,
        submitGradeName: null,
        grade: null,
        score: null,
        listenDuration: null,
        submitDate: null,
        dueDate: null,
        submitDatetime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentNo: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" }
        ],
        classCode: [
          { required: true, message: "班级编码不能为空", trigger: "blur" }
        ],
        className: [
          { required: true, message: "班级名称不能为空", trigger: "blur" }
        ],
        submitStatus: [
          { required: true, message: "提交状态不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getClassList()
    this.getDicts("submit_grade").then(response => {
      this.gradeOptions = response.data
    })
    // 加载评语选项
    this.getCommentOptions()
  },
  methods: {
    /** 加载评语选项 */
    getCommentOptions() {
      // 加载更多以避免分页遗漏
      listComment({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.commentOptions = response.rows || []
      })
    },
    /** 查询班级列表 */
    getClassList() {
      listClass().then(response => {
        this.classList = response.rows || []
      })
    },
    /** 根据班级编码查询学生列表 */
    getStudentListByClass(classCode) {
      if (!classCode) {
        this.studentList = []
        return
      }
      listStudent({ classId: classCode }).then(response => {
        this.studentList = response.rows || []
      })
    },
    /** 班级编码改变事件 */
    handleClassChange(classCode) {
      // 清空学生相关字段
      this.form.studentNo = null
      this.form.studentName = null
      this.studentList = []

      if (classCode) {
        // 设置班级名称
        const selectedClass = this.classList.find(item => item.classCode === classCode)
        if (selectedClass) {
          this.form.className = selectedClass.className
        }
        // 加载对应班级的学生列表
        this.getStudentListByClass(classCode)
      } else {
        this.form.className = null
      }
    },
    /** 学生选择改变事件 */
    handleStudentChange(studentNo) {
      if (studentNo) {
        const selectedStudent = this.studentList.find(item => item.studentNo === studentNo)
        if (selectedStudent) {
          this.form.studentName = selectedStudent.studentName
        }
      } else {
        this.form.studentName = null
      }
    },
    /** 查询作业提交记录列表 */
    getList() {
      this.loading = true
      listSubmit(this.queryParams).then(response => {
        this.submitList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        submitId: null,
        studentNo: null,
        studentName: null,
        classCode: null,
        className: null,
        submitStatus: '0', // 默认为未交
        submitContent: null,
        submitComment: null,
        grade: null,
        score: null,
        submitDate: null,
        dueDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        submitDatetime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.submitId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加作业提交记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const submitId = row.submitId || this.ids
      getSubmit(submitId).then(response => {
        this.form = response.data
        // 统一提交状态为字符串代码
        if (this.form && this.form.submitStatus !== undefined && this.form.submitStatus !== null) {
          this.form.submitStatus = String(this.form.submitStatus)
        }
        // 如果有班级编码，加载对应的学生列表
        if (this.form.classCode) {
          this.getStudentListByClass(this.form.classCode)
        }
        this.open = true
        this.title = "修改作业提交记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 规范化提交状态值为代码 '0' | '1' | '2'
          this.form.submitStatus = this.ensureSubmitStatusCode(this.form.submitStatus)
          if (this.form.submitId != null) {
            updateSubmit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSubmit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 将提交状态从中文标签映射为代码 */
    ensureSubmitStatusCode(value) {
      // 已是代码
      const byCode = this.submitStatusOptions.find(s => s.value === value)
      if (byCode) return byCode.value
      // 若是中文标签，映射到代码
      const byLabel = this.submitStatusOptions.find(s => s.label === value)
      return byLabel ? byLabel.value : value
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const submitIds = row.submitId || this.ids
      this.$modal.confirm('是否确认删除作业提交记录编号为"' + submitIds + '"的数据项？').then(function() {
        return delSubmit(submitIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('eduManage/submit/export', {
        ...this.queryParams
      }, `submit_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "作业提交记录导入"
      this.importVisible = true
    },
    /** 下载模板操作 */
    importTemplate() {
      if (!this.upload.classCode) {
        this.$modal.msgError("请先选择班级")
        return
      }
      this.download('eduManage/submit/importTemplate', {
        classCode: this.upload.classCode
      }, this.upload.classCode + '_作业提交记录'+`.xlsx`)
    },
    /** 班级选择改变事件 */
    handleClassCodeChange(classCode) {
      // 更新upload.data中的classCode
      this.upload.data.classCode = classCode || ''
    },
    /** 文件上传前处理 */
    beforeUpload(file) {
      // 检查是否选择了班级
      if (!this.upload.classCode) {
        this.$modal.msgError("请先选择班级")
        return false
      }
      // 检查是否选择了应交日期
      if (!this.upload.dueDate) {
        this.$modal.msgError("请先选择应交日期")
        return false
      }

      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isExcel = extension === 'xlsx' || extension === 'xls'
      if (!isExcel) {
        this.$modal.msgError('文件格式错误，请上传Excel文件(.xlsx, .xls)')
        return false
      }

      // 在上传前设置classCode参数
      this.upload.data = { classCode: this.upload.classCode, dueDate: this.upload.dueDate }
      return true
    },
    /** 文件上传失败处理 */
    handleFileError(err, file, fileList) {
      this.upload.isUploading = false
      this.$modal.msgError('上传文件失败')
      console.error('上传文件失败:', err)
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.importVisible = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.classCode) {
        this.$modal.msgError("请先选择班级")
        return
      }
      if (!this.upload.dueDate) {
        this.$modal.msgError("请先选择应交日期")
        return
      }
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 xls或xlsx的文件。")
        return
      }
      // 设置上传数据，将classCode作为参数传递
      this.upload.data = { classCode: this.upload.classCode, dueDate: this.upload.dueDate }
      this.$refs.upload.submit()
    },
    /** 应交日期改变事件 */
    handleDueDateChange(value) {
      this.upload.data.dueDate = value || ''
    },
    /** 获取提交状态标签类型 */
    getSubmitStatusTagType(status) {
      switch(status) {
        case '0':
        case '未交': return 'danger'   // 未交 - 红色
        case '1':
        case '已提交': return 'success'  // 已提交 - 绿色
        case '2':
        case '迟交': return 'warning'  // 迟交 - 橙色
        case '3':
        case '补觉': return 'warning'  // 补觉 - 橙色
        default: return 'info'
      }
    },
    /** 获取提交状态文本 */
    getSubmitStatusText(status) {
      switch(status) {
        case '0': return '未交'
        case '1': return '已提交'
        case '2': return '迟交'
        case '3': return '补觉'
        case '未交': return '未交'
        case '已提交': return '已提交'
        case '迟交': return '迟交'
        case '补觉': return '补觉'
        default: return status || '未知'
      }
    },
  }
}
</script>
